using System;
using System.Collections.Generic;
using System.Linq;

namespace WeBlog.Models
{
    public interface IBlogRepository
    {
        BlogPost GetBlogPostById(int blogPostId);
        IEnumerable<BlogPost> GetBlogPosts();
        void CreateBlogPost(BlogPost blogPost);
        void CreateBlogPostComment(BlogPostComment blogPostComment);

        IEnumerable<BlogPostComment> GetBlogPostComments(int blogPostId);

    }

    public class BlogRepository : IBlogRepository
    {
        private readonly static BlogRepository _instance = new BlogRepository();

        private BlogRepository()
        {
            
        }

        public static IBlogRepository Instance
        {
            get { return _instance; }
        }

        private BlogDbContext _context = new BlogDbContext();

        public BlogPost GetBlogPostById(int blogPostId)
        {
            return _context.BlogPosts.First(item => item.Id == blogPostId);
        }

        public IEnumerable<BlogPost> GetBlogPosts()
        {
            return _context.BlogPosts.OrderByDescending(item => item.BlogDateTime);
        }

        public void CreateBlogPost(BlogPost blogPost)
        {
            blogPost.BlogDateTime = DateTime.Now;
            _context.BlogPosts.Add(blogPost);
            _context.SaveChanges();
        }

        public void CreateBlogPostComment(BlogPostComment blogPostComment)
        {
            _context.Comments.Add(blogPostComment);
            _context.SaveChanges();

        }

        public IEnumerable<BlogPostComment> GetBlogPostComments(int blogPostId)
        {
            return _context.Comments.Where(item => item.BlogPostId == blogPostId);
        }


    }
}